define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'editable'], function ($, undefined, Backend, Table, Form, undefined) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'dahui/qiyebujiao/index',
                    add_url: 'dahui/qiyebujiao/add',
                    edit_url: 'dahui/qiyebujiao/edit',
                    del_url: 'dahui/qiyebujiao/del',
                    multi_url: 'dahui/qiyebujiao/multi',
                    import_url: 'dahui/qiyebujiao/import',
                    table: 'dahui_qiyebujiao',
                }
            });

            var table = $("#table");

            //给添加按钮添加`data-area`属性
            $(".btn-add").data("area", ["100%", "100%"]);
            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });

            //当表格数据加载完成时
            table.on('load-success.bs.table', function (e, data) {
                $("#money").text(data.extend.money);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                showToggle: false,
                search: false,
                sortName: 'id',
                dblClickToEdit: false, //是否启用双击编辑
                searchFormVisible: true,
                exportTypes: ['csv'],
                columns: [
                    [
                        //{checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true, operate: false},
                        {field: 'ownedcompany', title: __('Ownedcompany'), operate: false, formatter: Table.api.formatter.search, sortable: true},
                        {field: 'businesstype', title: __('Businesstype'), operate: false, searchList: {"个税":__('个税'),"公积金":__('公积金'),"社保":__('社保'),"补充公积金":__('补充公积金')}, formatter: Table.api.formatter.normal, sortable: true},
                        {field: 'overdueyear', title: __('Overdueyear'), defaultValue: Controller.api.defaultdate(), addclass:'datetimepicker', formatter: Table.api.formatter.search},
                        {field: 'idnumber', title: __('身份证号*'), operate: 'LIKE %...%', placeholder: '模糊搜索，*表示任意字符', formatter: Controller.api.formatter.idnumber},
                        {field: 'qiyekehu.name', title: __('Qiyekehu.name'), operate: false, formatter: Table.api.formatter.search, sortable: true},
                        {field: 'qiyekehu.mobile', title: __('Qiyekehu.mobile'), operate: false, formatter: Table.api.formatter.search, sortable: true},
                        {field: 'qiyekehu.address0', title: __('Qiyekehu.address0'), operate: false, formatter: Table.api.formatter.search, sortable: true},
                        {field: 'qiyekehu.address1', title: __('Qiyekehu.address1'), operate: false, formatter: Table.api.formatter.search, sortable: true},
                        {field: 'paymentnumber', title: __('Paymentnumber'), operate: false, formatter: Table.api.formatter.search, sortable: true},
                        {field: 'payingcompany', title: __('Payingcompany'), operate: false, formatter: Table.api.formatter.search, sortable: true},
                        {field: 'paymentbase', title: __('Paymentbase'), operate: false},
                        {field: 'paymentamount', title: __('Paymentamount'),  operate: false},
                        {
                            field: 'monthspaid',
                            title: __('缴纳月数*'),
                            editable: {
                                emptytext: '--',
                                disabled: !Config.caozuo , //true 则不能编辑 ---- 操作权限
                                success: function (response, newValue) {
                                    $(".btn-refresh").trigger("click");
                                }
                            },
                            operate: false,
                        },
                        {field: 'hejije', title: __('合计金额'), operate: false, formatter: Controller.api.formatter.heji},
                        {field: 'yearpayment', title: __('Yearpayment'), operate: false},
                        {
                            field: 'supplementarynote',
                            title: __('补缴备注*'),
                            editable: {
                                rows:10,
                                tpl: "<textarea rows='10' cols='50'></textarea>",
                                emptytext: '无',
                                disabled: !Config.caozuo , //true 则不能编辑 ---- 操作权限
                                success: function (response, newValue) {
                                    $(".btn-refresh").trigger("click");
                                }
                            },
                            operate: false,
                        },
                        {field: 'overduestatus', title: __('Overduestatus'), searchList: {"未办理":__('未办理'),"已办理":__('已办理'),"部分失败":__('部分失败')}, formatter: Controller.api.formatter.bjstatus, sortable: true},
                        //{field: 'luruman', title: __('录入员'), operate: false, sortable: true},
                        //{field: 'auditman', title: __('审核员'), operate: false, sortable: true},
                        {field: 'opman', title: __('操作员'), operate: false, sortable: true},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate},
                        {
                            field: 'payingcompany',
                            title: __('Businesstype') + "|" + __('公司'),
                            visible: false,
                            searchList: function (column) {
                                return Template('categorytpl', {});
                            }
                        },

                    ]
                ]
            });

            //点击身份证
            $(document).on("dblclick", ".aidnumber[data-id]", function () {
                var url = 'dahui/qiyebujiao/index1?idnumber=' + $(this).data('id');
                var options = {
                    shadeClose: false,
                    shade: [0.3, '#393D49'],
                    area: ["100%", "100%"],
                    callback:function(data){
                        //CallBackFun(value.id, value.name);//在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                        //$("#c_note").text(data);
                        //$(".btn-refresh").trigger("click");
                    }
                };
                Fast.api.open(url, "企业补缴明细", options);

            });

            //点击补缴状态
            $(document).on("dblclick", ".bjstatus[data-id]", function () {
                if (Config.caozuo ) {
                    var url = 'dahui/qiyebujiao/changebjstatus';
                    var id = $(this).data('id');
                    var _this = $(this);
                    Fast.api.ajax({
                        url: url,
                        data: {ids: id},
                    }, function (data, ret) {
                        //table.bootstrapTable('refresh');
                        console.log(ret.data.overduestatus);
                        _this.html(ret.data.overduestatus);
                    });
                }
            });

            var form = $("form.form-commonsearch");
            if ($(".datetimepicker", form).size() > 0) {
                require(['bootstrap-datetimepicker'], function () {
                    var options = {
                        format: 'YYYY-MM',
                        icons: {
                            time: 'fa fa-clock-o',
                            date: 'fa fa-calendar',
                            up: 'fa fa-chevron-up',
                            down: 'fa fa-chevron-down',
                            previous: 'fa fa-chevron-left',
                            next: 'fa fa-chevron-right',
                            today: 'fa fa-history',
                            clear: 'fa fa-trash',
                            close: 'fa fa-remove'
                        },
                        showTodayButton: true,
                        showClose: true
                    };
                    $('.datetimepicker', form).parent().css('position', 'relative');
                    $('.datetimepicker', form).datetimepicker(options);
                });
            }

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        index1: function () {
            // 初始化表格参数配置
            var idnumber =  $("#idnumber").val();

            Controller.api.bindevent();

            Table.api.init({
                extend: {
                    index_url: 'dahui/qiyebujiao/index1list?idnumber='+idnumber,
                    add_url: '',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                    table: 'dahui_qiyebujiao',
                }
            });

            console.log('' + $.fn.bootstrapTable.defaults.extend.index_url);

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                search:false,
                showToggle: false,
                showColumns: false,
                commonSearch: false,
                exportTypes: ['csv'],
                dblClickToEdit: false, //是否启用双击编辑
                searchFormVisible: true,
                columns: [
                    [
                        {field: 'ownedcompany', title: __('Ownedcompany'), operate: false},
                        {field: 'businesstype', title: __('Businesstype'), operate: false},
                        {field: 'overdueyear', title: __('Overdueyear'), operate: false},
                        {field: 'paymentnumber', title: __('Paymentnumber'), operate: false},
                        {field: 'payingcompany', title: __('Payingcompany'), operate: false},
                        {field: 'paymentbase', title: __('Paymentbase'), operate: false},
                        {field: 'paymentamount', title: __('Paymentamount'),  operate: false},
                        {field: 'monthspaid', title: __('缴纳月数'), operate: false},
                        {field: 'heji', title: __('合计金额'), operate: false, formatter: function (value, row, index) {
                            return [
                                row.paymentamount * row.monthspaid
                            ].join("")
                        }},
                        {field: 'yearpayment', title: __('Yearpayment'), operate: false},
                        {field: 'supplementarynote', title: __('Supplementarynote'), operate: false},
                        {field: 'overduestatus', title: __('Overduestatus'), operate: false},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

        },
        add: function () {

            updatecompany();
            updateinfo();

            function updatecompany() {
                var businesstype = $("#c-businesstype").val();
                $("#c-payingcompany").empty();
                $("#c-payingcompany").append('<option value= ""></option>');
                $.each(cdata.companyList, function (i, item) {
                    if (item.businesstype === businesstype) {
                        $("#c-payingcompany").append('<option value="' + item.name + '" >' + item.name + '</option>');
                    }
                });
            }

            function updateinfo() {
                var businesstype = $("#c-businesstype").val();
                var company = $("#c-payingcompany").val();
                $.each(cdata.companyList, function (i, item) {
                    if (item.name === company && item.businesstype === businesstype) {
                        $("#c-paymentbase").val(item.minimumcardinality);
                        $("#c-paymentamount").val(item.minimumcardinality * item.proportion);
                        return false;
                    }
                });
            }

            $(document).on("change", "#c-businesstype", function () {
                $("#c-paymentbase").val('');
                $("#c-paymentamount").val('');
                $("#c-paymentamount").val('');

                var thismonth = Controller.api.defaultdate();
                $("#c-paymentdate").val(thismonth);
                $("#c-paymentdate2").val(thismonth);

                updatecompany();
                $("#c-payingcompany").selectpicker("refresh");
                updateinfo();
            });

            $(document).on("change", "#c-payingcompany", function () {
                updateinfo();
            });

            $(document).on("change", "#c-paymentbase", function () {
                var paymentbase = $("#c-paymentbase").val();
                var businesstype = $("#c-businesstype").val();
                var company = $("#c-payingcompany").val();
                $.each(cdata.companyList, function (i, item) {
                    if (item.name === company && item.businesstype === businesstype) {
                        var num = paymentbase * item.proportion;
                        if (businesstype == '社保') {
                            num = Math.round(num * 10) / 10;
                        } else {
                            num = Math.round(num);
                        }
                        $("#c-paymentamount").val(num);
                        return false;
                    }
                });
            });

            function getuserinfo(idnumber) {
                if (idnumber.length < 20 && Controller.api.validateIdCard(idnumber)) {
                    //http://dahui.test/api/dahui/getuserinfo?idnumber=130230198105213016
                    var url = '/api/dahui/getuserinfo?idnumber=' + idnumber;
                    Fast.api.ajax({
                        url: url
                    }, function (data, ret) {
                        console.log(data);
                        $("#c-name").val(data.name);
                        $("#c-mobile").val(data.mobile);
                        $("#c-address0").val(data.address0);
                        $("#c-address1").val(data.address1);
                        $("#c-name").val(data.name);
                        $("#c-idnumber").focusout();//移除焦点

                    });
                }
            }

            document.getElementById('c-idnumber').addEventListener('paste', function (e) {
                if (!(e.clipboardData && e.clipboardData.items)) {
                    return;
                }
                for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
                    var item = e.clipboardData.items[i];

                    if (item.kind === "string") {
                        item.getAsString(function (str) {
                            var idnumber = str.trim();
                            getuserinfo(idnumber);
                        })
                    } else if (item.kind === "file") {

                    }
                    break;
                }
            });

            $("#c-idnumber").keypress(function (e) {
                console.log("111");
                if (e.which == 13) {
                    console.log("222");
                    var idnumber = $("#c-idnumber").val();
                    idnumber = idnumber.trim();
                    if (Controller.api.validateIdCard(idnumber))  {
                        getuserinfo(idnumber);
                    }
                }
            });

            $(document).on("change", "#c-idnumber", function () {
                console.log("555");
                var idnumber = $("#c-idnumber").val();
                idnumber = idnumber.trim();
                if (Controller.api.validateIdCard(idnumber))  {
                    getuserinfo(idnumber);
                }
            });


            Controller.api.bindevent();

        },
        edit: function () {

            updatecompany();
            //updateinfo();

            function updatecompany() {
                var payingcompany0 = $("#c-payingcompany0").val();
                var businesstype = $("#c-businesstype").val();
                $("#c-payingcompany").empty();
                $.each(cdata.companyList, function (i, item) {
                    if (item.businesstype === businesstype) {
                        if (payingcompany0 == item.name) {
                            $("#c-payingcompany").append('<option value="' + item.name + '" selected >' + item.name + '</option>');
                        } else {
                            $("#c-payingcompany").append('<option value="' + item.name + '" >' + item.name + '</option>');
                        }
                        //<option value="{$key}" {in name="key" value="$row.payingcompany"}selected{/in}>{$vo}</option>
                    }
                });
            }

            function updateinfo() {
                var businesstype = $("#c-businesstype").val();
                var company = $("#c-payingcompany").val();
                $.each(cdata.companyList, function (i, item) {
                    if (item.name === company && item.businesstype === businesstype) {
                        $("#c-paymentbase").val(item.minimumcardinality);
                        var num = item.minimumcardinality * item.proportion;
                        if (businesstype == '社保') {
                            num = Math.round(num * 10) / 10;
                        } else {
                            num = Math.round(num);
                        }
                        $("#c-paymentamount").val(num);
                        return false;
                    }
                });
            }

            $(document).on("change", "#c-businesstype", function () {
                updatecompany();
                $("#c-payingcompany").selectpicker("refresh");
                updateinfo();
            });

            $(document).on("change", "#c-payingcompany", function () {
                updateinfo();
            });

            $(document).on("change", "#c-paymentbase", function () {
                var paymentbase = $("#c-paymentbase").val();
                var businesstype = $("#c-businesstype").val();
                var company = $("#c-payingcompany").val();
                $.each(cdata.companyList, function (i, item) {
                    if (item.name === company && item.businesstype === businesstype) {
                        var num = paymentbase * item.proportion;
                        if (businesstype == '社保') {
                            num = Math.round(num * 10) / 10;
                        } else {
                            num = Math.round(num);
                        }
                        $("#c-paymentamount").val(num);
                        return false;
                    }
                });
            });

            function getuserinfo(idnumber) {
                if (idnumber.length < 20 && Controller.api.validateIdCard(idnumber)) {
                    //http://dahui.test/api/dahui/getuserinfo?idnumber=130230198105213016
                    var url = '/api/dahui/getuserinfo?idnumber=' + idnumber;
                    Fast.api.ajax({
                        url: url
                    }, function (data, ret) {
                        console.log(data);
                        $("#c-name").val(data.name);
                        $("#c-mobile").val(data.mobile);
                        $("#c-address0").val(data.address0);
                        $("#c-address1").val(data.address1);
                        $("#c-name").val(data.name);
                        $("#c-idnumber").focusout();//移除焦点

                    });
                }
            }

            document.getElementById('c-idnumber').addEventListener('paste', function (e) {
                if (!(e.clipboardData && e.clipboardData.items)) {
                    return;
                }
                for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
                    var item = e.clipboardData.items[i];

                    if (item.kind === "string") {
                        item.getAsString(function (str) {
                            var idnumber = str.trim();
                            getuserinfo(idnumber);
                        })
                    } else if (item.kind === "file") {

                    }
                    break;
                }
            });

            $("#c-idnumber").keypress(function (e) {
                console.log("111");
                if (e.which == 13) {
                    console.log("222");
                    var idnumber = $("#c-idnumber").val();
                    idnumber = idnumber.trim();
                    if (Controller.api.validateIdCard(idnumber))  {
                        getuserinfo(idnumber);
                    }
                }
            });

            $(document).on("change", "#c-idnumber", function () {
                console.log("555");
                var idnumber = $("#c-idnumber").val();
                idnumber = idnumber.trim();
                if (Controller.api.validateIdCard(idnumber))  {
                    getuserinfo(idnumber);
                }
            });


            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            defaultdate: function () {
                var date = new Date();
                var year = date.getFullYear();
                var month = date.getMonth() + 1;//获取当前月份(0-11,0代表1月)
                if (month >= 10) {
                    month = "" + month;
                } else {
                    month = "0" + month;
                }
                return year + "-" + month;
            },
            validateIdCard: function (idCard) {
                idCard = idCard.trim();
                var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;

                //如果通过该验证，说明身份证格式正确，但准确性还需计算
                if (regIdCard.test(idCard)) {
                    if (idCard.length == 18) {
                        var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //将前17位加权因子保存在数组里
                        var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
                        var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
                        for (var i = 0; i < 17; i++) {
                            idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i];
                        }
                        var idCardMod = idCardWiSum % 11;//计算出校验码所在数组的位置
                        var idCardLast = idCard.substring(17);//得到最后一位身份证号码
                        //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
                        if (idCardMod == 2) {
                            if (idCardLast == "X" || idCardLast == "x") {
                                //alert("恭喜通过验证啦！");
                                return true;
                            } else {
                                //alert("身份证号码错误！");
                                Backend.api.toastr.error("身份证号码验证错误,请修改！");
                                return false;
                            }
                        } else {
                            //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                            if (idCardLast == idCardY[idCardMod]) {
                                //alert("恭喜通过验证啦！");
                                return true;
                            } else {
                                //alert("身份证号码错误！");
                                Backend.api.toastr.error("身份证号码验证错误,请修改！");
                                return false;
                            }
                        }
                    }
                } else {
                    //alert("身份证格式不正确!");
                    Backend.api.toastr.error("身份证格式不正确!");
                    return false;
                }
            },
            formatter: {//渲染的方法
                idnumber: function (value, row, index) {
                    return [
                        '<a href="javascript:;" class="aidnumber" data-id= "' + row.idnumber + '" > ' + row.idnumber + '</a>'
                    ].join("")
                },
                bjstatus: function (value, row, index) {
                    return [
                        '<a href="javascript:;" class="bjstatus" data-id= "' + row.id + '" > ' + row.overduestatus + '</a>'
                    ].join("")

                },
                heji: function (value, row, index) {
                    return [
                        row.paymentamount * row.monthspaid
                    ].join("")
                }
            },
        }
    };
    return Controller;
});